/**
 * 
 */
package com.ntv.presentation.spring.web.user;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ntv.domain.IUser;
import com.ntv.domain.Login;
import com.ntv.service.DomainException;
import com.ntv.service.user.IUserAppService;

/**
 * @author Vedamoorthi Vairam
 * 
 */
@Controller
@RequestMapping("/signin.html")
@SessionAttributes("userSession")
public class SigninController {

	private final static Logger logger = Logger.getLogger(SigninController.class);
	
	@Autowired
	private IUserAppService userAppService;

	@Autowired
	private Validator validator;
	
	@RequestMapping(method = RequestMethod.GET)
	public void form(Model model) {
		model.addAttribute(MA_LOGIN, new Login());
	}
	
	public void setUserAppService(IUserAppService userAppService) {
		this.userAppService = userAppService;
	}

	private static final String MA_LOGIN= "login";

	@RequestMapping(method = RequestMethod.POST)	
	public String form(@ModelAttribute(MA_LOGIN) Login  login, BindingResult result, ModelMap model) 
	{
		validator.validate(login, result);
		if (result.hasErrors()) {
			result.reject("form.problems");
			return "signin";
		}
		else {
			try {		
				IUser newUser = userAppService.getUser(login.getEmail(), login.getPassword());				
				if (newUser == null) {
					ValidationUtils.rejectIfEmptyOrWhitespace(result, "message", "invalid.username");					
					return "signin";	
				}
				else
				{
					model.addAttribute("userSession", newUser);
					String target = login.getTarget();					
					if (target!= null) {
						return "redirect:/" + target;
					}
					return "redirect:/home.htm";
				}
			}
			catch (DomainException e) 
			{
				ValidationUtils.rejectIfEmptyOrWhitespace(result, "message", "invalid.username");
				return "signin";
			}
		}
	}
		
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		logger.info(" initBinder ");
		binder.setAllowedFields(new String[] { "email", "password", "target"});
	}	
}
